<!-- 聊天页面 -->
<template>
  <el-container style="background-color: #F6F7F8;height: 82.5vh;border: 1px grey solid;border-radius: 4px;"  v-loading="dataLoading" element-loading-text="拼命加载中">
    <el-header style="text-align: center;border-bottom:solid grey 1px;">
      <div style="margin-top: 15px;display: inline-block;">{{ userInfo.name }} </div>
      <!-- 收藏的小星星 -->
      <i :class="[userInfo.isCollected == 1 ? 'el-icon-star-on' : 'el-icon-star-off']" class="collectIcon"
        @click="$store.dispatch('collectStatusChange', userInfo)" style="font-size: 20px;margin-left: 10px;"></i>
      <!-- 拉黑button -->
      <el-button type="text" class="blockUser" @click="$store.dispatch('blockStatusChange', userInfo)"
        style="margin-left: 5px;">{{ userInfo.isBlocked == 1 ? "取消拉黑" : "拉黑" }}</el-button>
    </el-header>

    <el-main style="padding: 0px;">
      <div ref="window" style="height: 70vh;overflow-y: auto;">
        <div v-for="(item,index) in chatData" :key="index">

        <template v-if="index==0">
            <!-- <div style="font-size: small;color: gray;text-align: center;">{{ new Date(item.chatTime).toLocaleString() }}</div> -->
            <div style="font-size: small;color: gray;text-align: center;">{{getMoment(new Date(item.chatTime)) }}</div>
          </template>

          <template v-if="chatData[index-1]">
            <template v-if="((new Date(item.chatTime).getTime()-new Date(chatData[index-1].chatTime).getTime())/1000)>300">
            <div style="font-size: small;color: gray;text-align: center;">{{getMoment(new Date(item.chatTime)) }}</div>
          </template>
        </template>
          
          <template v-if="item.receiveRole != 'user'">
            <el-button @click="$store.dispatch('resumeDialogVisible', userInfo.userId)" type="text"  style="margin-left: 10px;">
              <el-avatar :src="getUserHeadIcon()" alt="替代文本" >
              </el-avatar>
            </el-button>
            <template v-if="item.chatType==1">
              <!-- 新页面查看版本 -->
              <div class="msg" v-if="item.chatInfo"> <a :href="getUserFileResume(item.chatInfo)" target="_blank" >{{ item.chatInfo }}</a></div>
              <!-- 下载版本 -->
              <!-- <div class="msg" v-if="item.chatInfo"> <a :href="getUserFileResume(item.chatInfo)" :download="`${userInfo.name}的简历pdf`" >{{ item.chatInfo }}</a></div> -->
            </template>
            <template v-else>
              <div class="msg"
              style="margin-left: 5px;border-radius: 0 9px 9px 9px;white-space: pre-line;text-align: left;margin-top: 5px">
              {{ item.chatInfo }}</div>
            </template>
            
                      </template>
          <template v-else>
            <div style="text-align: end;">
              <div class="msg"
                style="border-radius: 9px 0px 9px 9px;margin-right: 5px;white-space: pre-line;text-align: left;margin-top: 5px">
                {{ item.chatInfo }}</div>
              <el-avatar :src="require(`D:/staticFile/hr/headIconImg/${$store.state.headIcon}`)"></el-avatar>
              <!-- <el-avatar :src="require(`/../static/hr/headIconImg/${$store.state.headIcon}`)"></el-avatar> -->
            </div>
          </template>
        </div>
      </div>
    </el-main>

    <el-footer style="border-top:solid grey 1px;text-align: center;height: fit-content;">

      <el-dropdown @command="handleCommand">
        <span class="el-dropdown-link"> 常用语<i class="el-icon-arrow-up el-icon--right"></i></span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item :command="expression" v-for="expression in commonExpression" :key="expression">{{ expression
          }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <el-input type="textarea" resize="none" autosize placeholder="请输入内容" v-model="msg.chatInfo" clearable
        style="width: 95vh;margin-top: 10px;margin-bottom: 10px;margin-left: 10px;">
      </el-input>

      <el-button type="primary" size="mini" plain style="margin: 13px 15px;" @click="sendMsg()">发送消息</el-button>

      <el-button type="text"
        @click="_ => { dialog = true; bookingData.interviewAddress = $store.state.companyAddress }">发送面试邀请</el-button>
    </el-footer>

    <el-drawer title="面试信息" :before-close="handleClose" :visible.sync="dialog" direction="ltr"
      custom-class="demo-drawer" ref="drawer">
      <div style="padding: 20px;margin: 20px auto;width: fit-content;">
        <el-form label-width="240" :model="bookingData">
          <el-form-item label="用户名" prop="userId" style="width: 240px;">
            <!-- <el-input :disabled="true" style="width: 240px;" v-model="bookingData.userId"></el-input> -->
            <el-input :disabled="true" style="width: 240px;" v-model="userInfo.name"></el-input>
          </el-form-item>

          <el-form-item label="hr名" prop="hrId" style="width: 240px;">
            <!-- <el-input :disabled="true" v-model="bookingData.hrId"></el-input> -->
            <el-input :disabled="true" v-model="$store.state.hrName"></el-input>
          </el-form-item>
          <el-form-item label="应聘职位" style="width: 240px;">
            <el-select v-model="bookingData.recruitId" placeholder="请选择">
              <el-option v-for="item in recruitOptions" :key="item.recruitId" :label="item.recruitName"
                :value="item.recruitId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="地点" prop="interviewAddress" style="width: 240px;">
            <el-input v-model="bookingData.interviewAddress"></el-input>
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker v-model="bookingData.setInterviewTime" type="datetime" placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer" style="text-align: center;margin-top: 10vh;">
          <el-button @click="cancelForm">取 消</el-button>
          <!-- 这个时间才能触发beforeclose 在beforeclose里面提交 -->
          <el-button type="primary" @click="$refs.drawer.closeDrawer()">发送</el-button>
        </div>
      </div>
    </el-drawer>
  </el-container>


</template>

<script>
import { getCommonExpressions, getConcretChat, getDraft, updateDraft, write } from '@/api/chat';
import { getUserInfo } from '@/api/common';
import { getRecruitList } from '@/api/home';
import { recruitListQuery } from '@/api/recruit';
import { addInterview } from '@/api/self';
import moment from 'moment';

export default {
  props:["sonData"],
  data() {
    return {
      webSocket:null,
      dataLoading:false,
      dialog: false,
      //这个信息用切换路由初始化
      userInfo: {
        userId: null,
        name: null,
        headIcon: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
        isCollected: false,
        isBlocked: false,
        resumeId: 1,
      },
      // 面试的数据
      bookingData: {
        hrId: this.$store.state.hrId,
        userId: null,
        recruitId: null,
        setInterviewTime: null,
        interviewAddress: this.$store.state.companyAddress,
      },
      // 招聘职业
      recruitOptions: [],
      msg: {
        sendRole: "hr",
        sendId: this.$store.state.hrId,
        receiveRole: "user",
        receiveId: null,
        chatInfo: "",
        chatType: 0,
        isRead: 0
      },
      commonExpression: [],
      chatData: [],
    }
  },
  computed: {
  },
  methods: {
    getMoment(time){
      const now=moment()
      const chatMoment=moment(time)
      if (chatMoment.isSame(now,'day')) {
        return `今天 ${chatMoment.format('HH:mm')}`
      }else if (chatMoment.isSame(now.clone().subtract(1,"day"),"day")) {
        return `昨天 ${chatMoment.format('HH:mm')}`
      }else{
        return chatMoment.format('YYYY-MM-DD-HH:mm')
      }
    },
    getUserFileResume(chatInfo){
      var strings=chatInfo.split("/");
      var name=strings[strings.length-1]
      try {
        return require(`D:/staticFile/user/PDF/${name}`).default
      } catch (error) {
        console.log(111);
        
        return this.userInfo.headIcon;
        
      }
    },
    getUserHeadIcon(){
      try {
        return require(`D:/staticFile/user${this.userInfo.headIcon}`)
        
      } catch (error) {
        return this.userInfo.headIcon;
      }
    },
    handleCommand(command) {
      this.msg.chatInfo += command
    },
    handleClose() {
      console.log(this.bookingData);
      this.$confirm('是否提交')
        .then(_ => {
          // 检查一下日期地址和职位都不可为空
          if (this.bookingData.interviewAddress == null | this.bookingData.recruitId == null | this.bookingData.setInterviewTime == null
            | this.bookingData.interviewAddress == " " | this.bookingData.recruitId == "" | this.bookingData.setInterviewTime == "") {
            this.$message.error("日期，地址和职位不可为空")
          } else {
            // 确定的提交axios
            addInterview(this.bookingData).then(res => {
              if (res.code == 200) {
                this.$message.success("创建面试成功")
                // 根据recruitid获取下名称
                var jobName;
                this.recruitOptions.forEach(item => {
                  if (item.recruitId == this.bookingData.recruitId) {
                    jobName= item.recruitName
                  }
                })
                // 发送一个面试记录的聊天记录
                write({
                  sendRole: "hr",
                  sendId: this.$store.state.hrId,
                  receiveRole: "user",
                  receiveId: this.msg.receiveId,
                  chatInfo: `面试信息\n职位:${jobName}\n时间:${this.bookingData.setInterviewTime}\n地址:${this.bookingData.interviewAddress}`,
                  chatType: 1,
                  isRead: 0
                }).then(res => {
                  if (res.code == 200) {
                    this.getInfoScroll()
                  }
                })
              }
            })
          }
          this.dialog = false
        })
        .catch(_ => { });
    },
    cancelForm() {
      this.dialog = false;
    },
    sendMsg() {
      write(this.msg).then(res => {
        if (res.code == 200) {
          this.getInfoScroll()
          this.msg.chatInfo = ""
        }
        // else{
        //   this.$message.error(res.msg)
        // }

      })
      // 通过socket触发write，而不是axios触发，就用下面
      // this.$store.dispatch("sendMsg",this.msg)
    },
    //获取信息并初始化
    getPageInfo() {
      this.userInfo.userId = this.$route.params.id;
      this.bookingData.userId = this.$route.params.id;
      this.msg.receiveId = this.$route.params.id;
      getConcretChat({
        "myRole": "hr",
        "myId": this.$store.state.hrId,
        "yourRole": "user",
        "yourRoleId": this.$route.params.id
      }).then(res => {
        this.chatData = res.data
      })
    },
    // 获取信息并 滚动条移动到底部
    getInfoScroll() {
      this.userInfo.userId = this.$route.params.id;
      this.bookingData.userId = this.$route.params.id;
      this.msg.receiveId = this.$route.params.id;
      this.getConcretInfo()
      this.dataLoading=true
      getConcretChat({
        "myRole": "hr",
        "myId": this.$store.state.hrId,
        "yourRole": "user",
        "yourRoleId": this.$route.params.id
      }).then(res => {
        this.chatData = res.data
        
        setTimeout(() => { 
          if (this.$refs.window) {
            this.$refs.window.scrollTop = this.$refs.window.scrollHeight
          }
          this.dataLoading=false
        }, 300)
        
        
      })
    },
    getConcretInfo() {
      
      getUserInfo({ "userId": this.userInfo.userId }).then(res => {
        this.userInfo.name = res.data.username;
        this.userInfo.headIcon = res.data.headIcon;
        this.userInfo.isBlocked = res.data.isBlocked;
        this.userInfo.isCollected = res.data.isCollected
        
      })
    }
  },
  updated() {

  },
  mounted() {
    // this.$parent.$on('reload-event', (data) => {
    //   console.log('子组件收到父组件事件：');
    //   this.getPageInfo();
    // });
    this.webSocket = this.$store.state.webSocket
      
  
    this.getInfoScroll()
    getDraft({
      "myRole": "hr",
      "myId": this.$store.state.hrId,
      "yourRole": "admin",
      "yourRoleId": this.$route.params.id
    }).then(res => {
      this.msg.chatInfo = res.data
    })
    // 获取常用语
    getCommonExpressions({ "role": "hr" }).then(res => {
      this.commonExpression = res.data
    })
    //获取聘请职位
    setTimeout(_=>{recruitListQuery({
      "hrId": this.$store.state.hrId,
      "identity": 1,
      "companyId": this.$store.state.companyId
    }).then(res => {
      this.recruitOptions = res.data
    })},1000)
    
  },
  beforeDestroy() {
    // 把草稿更新到后端
    updateDraft(this.msg).then(res => {
    })
  },

  watch: {
    $route(to, from) {
      // 对路由变化作出响应...
      //把上一个页面草稿更新到后端
      updateDraft(this.msg).then(res => {
      })

      this.getInfoScroll()
      this.msg.chatInfo = "";
      // 得到下一个页面的草稿
      getDraft({
        "myRole": "hr",
        "myId": this.$store.state.hrId,
        "yourRole": "user",
        "yourRoleId": this.$route.params.id
      }).then(res => {
        this.msg.chatInfo = res.data
      })
    },
  sonData(){
    // console.log(11112222);
    this.getPageInfo()
  }
  },
  
}
</script>

<style>
.msg {
  display: inline-block;
  width: fit-content;
  background-color: white;
  padding: 15px;
  padding-top: 8px;
  padding-bottom: 8px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, .12), 0 0 2px rgba(0, 0, 0, .04);
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}

.el-icon-arrow-down {
  font-size: 12px;
}
</style>